package Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class MysqlGetConnection {
    private static Connection conn = null;


    public static Connection getConn(){
        try {
            if(conn==null||conn.isClosed()){
                synchronized (MysqlGetConnection.class){
                    if(conn==null||conn.isClosed()){
                        conn=createConnection();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    private static Connection createConnection() throws Exception {
        String DB_URL,USER,PASS,JDBC_DRIVER;
        DB_URL="jdbc:mysql://localhost:3306/jl?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
        USER="root";
        PASS="1224432083";
        JDBC_DRIVER="com.mysql.jdbc.Driver";
        Class.forName(JDBC_DRIVER);
        return DriverManager.getConnection(DB_URL,USER,PASS);
    }

    static int createSignInHistory()
    {
        String sql= "CREATE TABLE IF NOT EXISTS signinhistory(\n" +
                "   name VARCHAR(100),\n" +
                "   signindate BIGINT NOT NULL" +
                ")ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        Connection conn = MysqlGetConnection.getConn();
        int i = -1;
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    static int createAccount()
    {
        String sql= "CREATE TABLE IF NOT EXISTS account(\n" +
                "   name VARCHAR(100),\n" +
                "   password VARCHAR(100) NOT NULL,\n" +
                "   regdate BIGINT NOT NULL,\n" +
                "   runningdays BIGINT NOT NULL,\n" +
                "   maxrunningdays BIGINT NOT NULL,\n" +
                "   PRIMARY KEY ( name ),\n" +
                "   KEY ( regdate )\n" +
                ")ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        Connection conn = MysqlGetConnection.getConn();
        int i = -1;
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            i = pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    public static void init()
    {
        int i=createAccount();
        if(i!=0)
        {
            System.out.println("创建Account表失败");
            return;
        }
        i=createSignInHistory();
        if(i!=0)
        {
            System.out.println("创建签到历史记录表失败");
            return;
        }
    }

}
